package cn.mugutu.finance.interceptor;

import cn.mugutu.finance.annotation.NoAuthenticationAPI;
import cn.mugutu.finance.annotation.SysResource;
import cn.mugutu.finance.domain.system.User;
import cn.mugutu.finance.dto.BaseResult;
import cn.mugutu.finance.service.system.ResourceService;
import cn.mugutu.finance.service.system.UserService;
import cn.mugutu.finance.utils.ConstantConfig;
import cn.mugutu.finance.utils.JSONUtil;
import cn.mugutu.finance.utils.RequestHolder;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * 权限拦截器
 */
@Slf4j
public class PrivilegeInterceptor implements HandlerInterceptor {

    private List<String> resourcesCodeList;
    @Autowired
    private ResourceService resourceService;
    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

//        log.info("请求参数===>" + request.getParameterMap().values().toString());

        //不需登陆都能访问
        HandlerMethod method = (HandlerMethod) handler;
        if (method.getMethod().isAnnotationPresent(NoAuthenticationAPI.class)) {
            return true;
        }
        if (method.getBeanType().isAnnotationPresent(NoAuthenticationAPI.class)) {
            return true;
        }

        //是否登陆
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(ConstantConfig.USER_IN_SESSION);
        if (user == null) {
            if (RequestHolder.isAjaxRequest(request)) {
                BaseResult jsonRes = new BaseResult(false, "登陆超时,请重新登陆");
                response.setContentType("application/json;charset=UTF-8");
                response.setCharacterEncoding("UTF-8");
                response.getWriter().write(JSONUtil.objectTOJsonString(jsonRes));
            } else {
                response.sendRedirect(request.getContextPath() + "/noSessionUI");
                return false;
            }
            return false;
        }

        //系统所有加权限的资源(获取后应该存入二级缓存/这里是单利的,可以缓存成员变量共享)
        if (resourcesCodeList == null || resourcesCodeList.size() == 0) {
            resourcesCodeList = resourceService.findAllResourceCode();
        }

        SysResource sysResourceAnnotation = method.getMethod().getAnnotation(SysResource.class);
        String sysResourceCode;
        if (sysResourceAnnotation == null) { //所有登陆用户都能访问的资源
            return true;
        } else {    //需要有权限才能访问的资源
            sysResourceCode = sysResourceAnnotation.code();
        }

        //获取用户的权限
        List<String> userPrivilege = (List<String>) session.getAttribute(ConstantConfig.LOGIN_USER_PRIVILEGE);
        if (userPrivilege == null || userPrivilege.size() == 0) {
            userPrivilege = userService.findSysResourceByLoginUser(user);
            session.setAttribute(ConstantConfig.LOGIN_USER_PRIVILEGE, userPrivilege);
        }

        if (!userPrivilege.contains(sysResourceCode)) {
            if (RequestHolder.isAjaxRequest(request)) {
                BaseResult jsonRes = new BaseResult(false, "你没有权限访问" + sysResourceAnnotation.name());
                response.setContentType("application/json;charset=UTF-8");
                response.setCharacterEncoding("UTF-8");
                response.getWriter().println(JSON.toJSON(jsonRes));
            } else {
                response.sendRedirect(request.getContextPath() + "/user/noPrivilegeAccessUI");
            }
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
            throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
    }

}
